﻿Imports System.Net.Sockets
Imports System.Net

Public Class Server

    Private ip As String
    Private port As String

    Private conn As TcpListener
    Private _client As TcpClient
    Private _packets As New Packets
    Private stre As System.Net.Sockets.NetworkStream

    Private state As status = status.STOPPED

    Private Enum status
        RUNNING
        STOPPED
        PAUSED
    End Enum

    Public Sub New(ByVal ip As String, ByVal port As String)
        Me.ip = ip
        Me.port = port
    End Sub

    Public Sub startServer()
        If Tools.IpTools.VerifyIp(Me.ip) AndAlso state = status.STOPPED Then

            conn = New TcpListener(IPAddress.Parse(ip), port)
            conn.Start()
            Console.WriteLine("Il Server Si e' avviato correttamente")
            Me.state = status.RUNNING

            client = conn.AcceptTcpClient
            stre = client.GetStream

            While True

                Dim buffer(1024) As Byte
                stre.Read(buffer, 0, buffer.Length - 1)
                _packets.ReceivePacket(buffer)

                _packets.SendPacket("Pacchetto arrivato".ToCharArray, stre)

            End While

        End If
    End Sub

    Public Sub StopServer()

        If Me.state = status.RUNNING Then

            conn.Stop()
            Me.state = status.STOPPED

        End If

    End Sub

    Public Sub SendPackets(ByVal msg As String)

        _packets.SendPacket(msg.ToCharArray, stre)

    End Sub

#Region "Property "

    Public Property client As TcpClient
        Get
            Return _client
        End Get
        Set(value As TcpClient)
            _client = value
        End Set
    End Property

    Public ReadOnly Property GetIp As String
        Get
            Return ip
        End Get
    End Property

    Public ReadOnly Property GetPort As String
        Get
            Return port
        End Get
    End Property

#End Region

End Class
